﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace StockHelper.Scripts.Comm
{
    public class Timer
    {
        private static List<Data> datas = new List<Data>();

        private static Thread  thread;

        public static void Add(Action action, int nextTime = 0, int loopTime = -1) {
            datas.Add(
                new Data {
                    action = action,
                    nextTime = nextTime,
                    loopTime = loopTime,
                });
        }

        public static void Start()
        {
            thread = new Thread(new ThreadStart(Loop));
            thread.Start();
        }

        public static void Clear() {
            datas.Clear();
        }

        public static void Remove(Action action)
        {
            for (int i = datas.Count - 1; i >= 0; i--)
            {
                if (datas[i].action == action)
                {
                    datas.RemoveAt(i);
                }
            }
        }

        public static void Replace(Action action, int nextTime, int loopTime = -1) {
            Remove(action);
            Add(action, nextTime, loopTime);
        }

        private static void Loop()
        {
            while (true)
            {
                int time = Time.GetTimeStamp();
                for (int i = datas.Count - 1; i >= 0; i--)
                {
                    if (datas[i].nextTime <= time)
                    {
                        datas[i].action();
                        if (datas[i].loopTime > 0)
                            datas[i].nextTime = datas[i].loopTime + time;
                        else
                            datas.RemoveAt(i);
                    }
                }
                
                Thread.Sleep(1000);
            }
        }

        public static void Stop()
        {
           if( thread != null)
            thread.Abort();
        }

        public class Data {
            public Action action;
            public int nextTime;
            public int loopTime;
        }

    }
}
